package _11_整理题目._2_二叉树_递归_dfs_bfs;

import org.junit.Test;
import util.TreeNode;


/**
 * 已知两颗二叉树，将它们合并成一颗二叉树。
 * 合并规则是：都存在的结点，就将结点值加起来，否则空的位置就由另一个树的结点来代替。
 * 
 * 
 */
public class _08_合并二叉树 {
    
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        
        t1.val += t2.val;
        
        if(t1.left != null && t2.left != null) mergeTrees(t1.left, t2.left);
        else if(t1.left == null && t2.left != null) t1.left = t2.left;
        
        if(t1.right != null && t2.right != null) mergeTrees(t1.right, t2.right);
        else if(t1.right == null && t2.right != null) t1.right = t2.right;
        
        return t1;
    }
    
    @Test
    public void main() {
        Integer[] input1 = {1, 3, 2, 5};
        Integer[] input2 = {2, 1, 3, null, 4, null, 7};
        TreeNode root1 = TreeNode.getTreeFromArray(input1);
        TreeNode root2 = TreeNode.getTreeFromArray(input2);
        TreeNode root3 = mergeTrees(root1, root2);
        TreeNode.printTree(root3);
    }
    
}
